import Utils from './js/Utils';

/**
 * 树视图数据源构建类
 */
var self;
export default class TreeDataSource{
    constructor(cfg) {
        self = this;
        this._delay = cfg.delay;
        this.config = cfg;
        this._data = null;
        this._initDataFromXML();
    }
    /**
     * @author 李桥
     * @param options
     * @param callback
     */
    data(options, callback){
        var self = this;
        var $data = null;
        if (!("name" in options) && !("type" in options)) {
            $data = this._data;
            callback({data: $data});
            return;
        }
        else if ("type" in options && options.type == "folder") {
            if ("additionalParameters" in options && "children" in options.additionalParameters)
                $data = options.additionalParameters.children; else $data = {}
        }
        if ($data != null)
            callback({data: $data});
    }

    _classifyAndCountComponents(){

    }

    /**
     * 从xml加载数据
     * @author 李桥
     * @private
     */
    _initDataFromXML() {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", this.config.src, false);
        xhr.onload = function (e) {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    var json = Utils.xmlToJson(xhr.responseXML, {'Name': 'name', 'id': 'guid'});
                    var project = Utils.findNodeOfType(json.children[0], "decomposition")[0].children[0];
                    //分类构件
                    console.log(project);
                    //当前选中是MODELTREE还是IFCTREE
                    if(self.config.treeType === "IFCTREE"){
                        self._data = self._parse_IFCTREE_DataStructor(project);
                    }else if(self.config.treeType === "MODELTREE"){
                        self._data = self._parse_MODELTREE_DataStructor(project);
                    }
                } else {
                    console.error("请求错误")
                }
            }
        };
        xhr.send(null);
    }

    /**
     * MODELTREE转换函数
     * @param source
     * @private
     */
    _parse_MODELTREE_DataStructor(source){
        var dataSource ={};
        //当前引用节点
        var reference = dataSource;
        //reference["type"] = "folder";
        //reference["name"] = "";
        var queue = [source];
        while(queue.length){
            var curEle = queue.shift();
            if(!curEle.hasCreated){
                var currentNode;
                if(curEle.ObjectType && curEle.ObjectType!=""){
                    currentNode = {objectType:curEle.ObjectType,name:curEle.name,type:'item',guid:curEle.guid};
                    //当前构件无分类，新建分类
                    if(reference[curEle.ObjectType]){
                        reference[curEle.ObjectType] = {objectType:curEle.ObjectType,name:curEle.name,type:'folder',additionalParameters:{children:{}},count:0};
                    }
                    reference[curEle.ObjectType]["additionalParameters"]["children"][curEle.guid] = currentNode;
                }
            }
            //有孩子元素，就遍历并为当前reference创建孩子元素，并记录创建标志，防止重复创建
            if(curEle.children&&curEle.children.length){
                var children = curEle.children;
                for (var i = 0;i < children.length; i ++){
                    if(children[i]["xlink:href"]) {
                        children.splice(i,1);
                        i--;
                        continue;
                    }
                    if (children[i].type === "IfcOpeningElement"){
                        children.splice(i,1);
                        i--;
                        continue;
                    }
                }
                //在经过上面过滤之后还有孩子节点
                if (children.length){
                   // reference.type = "folder";
                   // reference["additionalParameters"] = {"children":{}};
                    for(var i = 0; i < children.length; i ++){
                        var cur = children[i];
                        if(cur.ObjectType && cur.ObjectType!=""){
                            var bnd = {objectType:cur.ObjectType,name:cur.name,type:"item",guid:cur.guid};
                            if(!reference[cur.ObjectType]){
                                reference[cur.ObjectType] = {objectType:cur.ObjectType,name:cur.name,type:'folder',additionalParameters:{children:{}},count:0};
                            }
                            reference[cur.ObjectType]["additionalParameters"]["children"][cur.guid] = bnd;
                            reference[cur.ObjectType]["count"] += 1;
                            //节点创建以后记录
                            cur.hasCreated = true;
                        }
                        queue.push(cur);
                    }
                }
            }
        }
        return reference;
    }
    /**
     * 数据转换，采用队列进行数据转换（深度遍历） 卧槽，写完了就忘记自己写的啥子了（^_^……）
     * @author 李桥
     * @param source
     * @returns {*}
     * @private
     */
    _parse_IFCTREE_DataStructor(source){
        var dataSource ={};
        //当前引用节点
        var reference = dataSource;
        var queue = [source];
        while(queue.length){
            var curEle = queue.shift();
            if(!curEle.hasCreated){
                var currentNode = {name:curEle.name,type:'item',guid:curEle.guid};
                reference[curEle.name] = currentNode;
                reference = currentNode;
            }
            else{
                reference = curEle.referenceNode;
            }
            //有孩子元素，就遍历并为当前reference创建孩子元素，并记录创建标志，防止重复创建
            if(curEle.children&&curEle.children.length){
                var children = curEle.children;
                for (var i = 0;i < children.length; i ++){
                    if(children[i]["xlink:href"]) {
                        children.splice(i,1);
                        i--;
                        continue;
                    }
                    if (children[i].type === "IfcOpeningElement"){
                        children.splice(i,1);
                        i--;
                        continue;
                    }
                }
                //在经过上面过滤之后还有孩子节点
                if (children.length){
                    reference.type = "folder";
                    reference["additionalParameters"] = {"children":{}};
                    for(var i = 0; i < children.length; i ++){
                        var cur = children[i];
                        var bnd = {name:cur.name,type:"item",guid:cur.guid};
                        reference["additionalParameters"]["children"][cur.guid] = bnd;
                        //节点创建以后记录
                        cur.hasCreated = true;
                        //记录数据节点对应的dom节点
                        cur.referenceNode = bnd;
                        queue.push(cur);
                    }
                }
            }
        }
        return dataSource["项目编号"]["additionalParameters"]["children"]["2ZKYCuA$v0cwhh$jJcKJF1"]["additionalParameters"]["children"]["3BnuHFPuLEH9z7GQK$i7uu"]["additionalParameters"]["children"];
    }

    /**
     * 获取楼层数据
     * @author 李桥
     */
    getStoreyDatas(){
        var storeys = this._data;
        var storeyDatas = {};
        for(var storeyName in storeys){
            storeyDatas[storeys[storeyName].name] = this.parseCurStoreyData(storeys[storeyName]);
        }
        return storeyDatas;
    }

    /**
     * 解析当前楼层数据
     * @author 李桥
     * @param storey 楼层
     */
    parseCurStoreyData(storey){
        var curStoreyData = [];
        var queue = [storey];
        while(queue.length){
            var curStorey = queue.shift();
            //楼层中当前构建有孩子节点
            if(curStorey.additionalParameters&&curStorey.additionalParameters.children){
                for(var curKey in curStorey.additionalParameters.children){
                    var curComponent = curStorey.additionalParameters.children[curKey];
                    if(curComponent.additionalParameters){
                        queue.push(curComponent);
                    }else{
                        curStoreyData.push({name:curComponent.name,guid:curComponent.guid});
                    }
                }
            }else{
                curStoreyData.push({name:curStorey.name,guid:curStorey.guid});
            }
        }
        return curStoreyData;
    }
}


